package com.ck.tool;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Xml转化工具类
 */
public class XmlConvert {
    /**
     * xml转 javaBean
     * @param xml
     * @param load
     * @param <T>
     * @return
     * @throws JAXBException
     */
    public static <T> T xmlToBean(String xml, Class<T> load) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(load);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        return (T) unmarshaller.unmarshal(new StringReader(xml));
    }


    public static <T> StringWriter beanToXml(T t) throws JAXBException, FileNotFoundException {
        JAXBContext context = JAXBContext.newInstance(t.getClass());
        Marshaller m = context.createMarshaller();
        StringWriter sw = new StringWriter();
        m.marshal(t,sw);
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
        m.marshal(t,new FileOutputStream("/user.xml"));
        m.marshal(t,System.out);
        return sw;
    }



}
